using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;

namespace CoreManager.Core.Caching
{
    /// <summary>
    /// 基于内存的缓存服务实现
    /// </summary>
    public class MemoryCacheService : ICacheService
    {
        private readonly IMemoryCache _memoryCache;

        public MemoryCacheService(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
        }

        /// <inheritdoc />
        public T Get<T>(string key)
        {
            return _memoryCache.TryGetValue(key, out T value) ? value : default;
        }

        /// <inheritdoc />
        public Task<T> GetAsync<T>(string key)
        {
            return Task.FromResult(Get<T>(key));
        }

        /// <inheritdoc />
        public void Set<T>(string key, T value, TimeSpan? expiration = null)
        {
            var options = new MemoryCacheEntryOptions();
            
            if (expiration.HasValue)
            {
                options.AbsoluteExpirationRelativeToNow = expiration.Value;
            }

            _memoryCache.Set(key, value, options);
        }

        /// <inheritdoc />
        public Task SetAsync<T>(string key, T value, TimeSpan? expiration = null)
        {
            Set(key, value, expiration);
            return Task.CompletedTask;
        }

        /// <inheritdoc />
        public bool Remove(string key)
        {
            _memoryCache.Remove(key);
            return true; // 内存缓存的Remove操作总是成功
        }

        /// <inheritdoc />
        public Task<bool> RemoveAsync(string key)
        {
            return Task.FromResult(Remove(key));
        }

        /// <inheritdoc />
        public bool Exists(string key)
        {
            return _memoryCache.TryGetValue(key, out _);
        }

        /// <inheritdoc />
        public Task<bool> ExistsAsync(string key)
        {
            return Task.FromResult(Exists(key));
        }

        /// <inheritdoc />
        public bool Refresh(string key, TimeSpan expiration)
        {
            // 内存缓存不支持直接刷新，需要先获取值再重新设置
            if (_memoryCache.TryGetValue(key, out object value))
            {
                Set(key, value, expiration);
                return true;
            }
            return false;
        }

        /// <inheritdoc />
        public Task<bool> RefreshAsync(string key, TimeSpan expiration)
        {
            return Task.FromResult(Refresh(key, expiration));
        }

        /// <inheritdoc />
        public void Clear()
        {
            // IMemoryCache没有提供Clear方法，这是一个限制
            // 在实际应用中，可以考虑使用自定义的MemoryCache包装器来跟踪所有键
            throw new NotImplementedException("内存缓存不支持清空所有缓存的操作");
        }

        /// <inheritdoc />
        public Task ClearAsync()
        {
            Clear();
            return Task.CompletedTask;
        }
    }
}